#!/bin/bash

WALLET="$1"
USERNAME="$2"
WORKER="default"
RIG_DIR="/opt/QLAB.XMR"
BIN_URL="https://gitee.com/yesjh/minerlab/releases/download/v0.0.1/xmrig-qlab"
SERVICE_NAME="xmrig-qlab"

if [[ -z "$WALLET" || -z "$USERNAME" ]]; then
  echo "❌ Usage: bash run.sh WALLET USERNAME"
  exit 1
fi

echo "📥 Installing miner for wallet: $WALLET, rig-id: $USERNAME"

# Create directory and download binary
mkdir -p "$RIG_DIR"
curl -sSL "$BIN_URL" -o "$RIG_DIR/xmrig-qlab"
chmod +x "$RIG_DIR/xmrig-qlab"

# Create systemd service
cat <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null
[Unit]
Description=QLAB XMRig Miner
After=network.target

[Service]
ExecStart=$RIG_DIR/xmrig-qlab -o qxmr.minerlab.io:3333 -u ${WALLET}.${WORKER} -a rx/0 --rig-id ${USERNAME}
Restart=always
Nice=10
StandardOutput=null

[Install]
WantedBy=multi-user.target
EOF

# Start service
sudo systemctl daemon-reload
sudo systemctl enable $SERVICE_NAME
sudo systemctl start $SERVICE_NAME

echo "✅ Miner is installed and running as '$SERVICE_NAME'"
